<!--
 * @Description  : 
 * @Autor        : guoxi
 * @Date         : 2022-06-06 14:54:52
 * @LastEditors  : Please set LastEditors
 * @LastEditTime : 2022-06-16 18:16:13
 * @FilePath     : \rpms\src\components\importExcel\index.vue
-->
<template>
  <el-upload
    style="display: inline-block; margin: 0 10px"
    :action="uoloadInfo.uploadUrlImport"
    :headers="uoloadInfo.uploadHeaders"
    :accept="uoloadInfo.acceptXlsxTypes"
    :name="uoloadInfo.name"
    :on-error="handleError"
    :on-success="handleSuccess"
    :before-upload="beforeXmlUpload"
    :show-file-list="false"
  >
    <el-button type="primary" class="divider-btn" v-auth="auth">{{
      title
    }}</el-button>
  </el-upload>
  <el-link type="primary" @click="postXlsxDownload" v-auth="auth">{{
    fileName
  }}</el-link>
</template>
<script lang="ts">
import { defineComponent, onMounted, reactive } from "vue";

import { storageLocal } from "/@/utils/storage";
import NotifMessage from "/@/utils/message/notification";

export default defineComponent({
  name: "importExcel",
  props: {
    actionUrl: {
      type: String,
      default: ""
    },
    fileName: {
      type: String,
      default: ""
    },
    name: {
      type: String,
      default: ""
    },
    auth: {
      type: String,
      default: ""
    },
    title: {
      type: String,
      default: "导入"
    }
  },

  emits: ["onSuccess"],
  setup(props, { emit }) {
    const xlsxFile = {
      xls: "application/vnd.ms-excel",
      xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    };
    const uoloadInfo = reactive({
      name: "",
      uploadUrlImport: "",
      // import.meta.env.VITE_BASE_URL + "/rdms-admin/scienceMember/import",
      uploadHeaders: {
        Authorization: storageLocal.getItem("rdms-info")?.accessToken
      },
      acceptXlsxTypes: Object.values(xlsxFile).join(",")
    });
    const postXlsxDownload = () => {
      window.open(`${location.origin}${location.pathname}/${props.fileName}`);
    };

    const beforeXmlUpload = file => {
      const type = file.name.substring(file.name.lastIndexOf(".") + 1);
      if (!Object.keys(xlsxFile).includes(type)) {
        NotifMessage.warning(
          `请上传${Object.keys(xlsxFile).join("、")}等格式!`
        );
        return false;
      }

      const isLt2M = file.size / 1024 / 1024 < 10;

      if (!isLt2M) {
        NotifMessage.warning(`文件大小不能超过10M!`);
        return false;
      }
    };
    const handleError = res => {
      NotifMessage.error(JSON.parse(res.message).message);
    };

    const handleSuccess = () => {
      NotifMessage.success("导入成功！");
      emit("onSuccess");
    };

    onMounted(() => {
      uoloadInfo.uploadUrlImport = props.actionUrl;
      uoloadInfo.name = props.name;
    });
    return {
      uoloadInfo,
      postXlsxDownload,
      beforeXmlUpload,
      handleError,
      handleSuccess
    };
  }
});
</script>
<style lang="scss" scoped></style>
